﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;
using Microsoft.TeamFoundation.Build.Client;

namespace TeamDeploy.Activities
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public sealed class Install : CustomActivityBase
    {
        [RequiredArgument]
        public InArgument<string> MSIPathFilename { get; set; }
        
        public InArgument<string> ExtraArgs { get; set; }

        [RequiredArgument]
        public InArgument<string> TargetMachine { get; set; }

        [RequiredArgument]
        public InArgument<string> RemoteExecutePathFilename { get; set; }

        public InArgument<string> OverrideDefaultArgs { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {

            try
            {
                string msiPathFilename = context.GetValue(this.MSIPathFilename);
                string extraArgs = context.GetValue(this.ExtraArgs);
                string targetMachine = context.GetValue(this.TargetMachine);
                string remoteExecutePathFilename = context.GetValue(this.RemoteExecutePathFilename);
                string overrideDefaultArgs = context.GetValue(this.OverrideDefaultArgs);
                bool ignoreExitCode = false;
                bool.TryParse(context.GetValue(this.IgnoreExitCode), out ignoreExitCode);
                    
                if (!System.IO.File.Exists(remoteExecutePathFilename))
                {
                    throw new ArgumentException(
                        "RemoteExecute does not exist at", "RemoteExecutePathFilename");
                }

                string installArgs = "/qb! /i";

                if (overrideDefaultArgs != null && overrideDefaultArgs.Length > 0)
                {
                    installArgs = overrideDefaultArgs;
                }

                string args = @"\\" + targetMachine + " -i 0 -s -accepteula " + "msiexec.exe " + installArgs + " " + @"""" + msiPathFilename + @"""" + " " + extraArgs;


               // Process p = Process.Start("msiexec.exe",installArgs + " " + @"""" + msiPathFilename + @"""" + " " + extraArgs);
               // Process p = Process.Start(remoteExecutePathFilename, args);
                using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                {
                    process.StartInfo.FileName = remoteExecutePathFilename;
                    //process.StartInfo.WorkingDirectory = SearchPathRoot.Get(context);                    
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.ErrorDialog = false;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.Arguments = args;

                    try
                    {
                        process.Start();
                        string output = process.StandardOutput.ReadToEnd();
                        process.WaitForExit();
                        LogMessage(context, "Install Output:" + output);
                    }
                    catch (Exception ex)
                    {
                        LogMessage(context, ex.ToString());
                        throw ex;
                    }
                    //p.WaitForExit();        



                    if (process.ExitCode != 0)
                    {
                        throw new Exception("failed to deploy msi to " + targetMachine);
                        // Log.LogMessage("Installing " + MSIPathFilename + " " + args + " on " + TargetMachine + " returned code:" + p.ExitCode);
                    }

                    //if (BuildEngine != null)
                    //{
                    //  Log.LogMessage("Installing " + MSIPathFilename + " " + args + " on " + TargetMachine + " completed successfully.");
                    //}
                }

            }
            catch (Exception)
            {
                throw;
                //if (buildEngine != null)
                //{
                //    Log.LogError("Error executing Install: MSIPathFilename=" + MSIPathFilename + " TargetMachine=" +
                //                 TargetMachine + " RemoteExecutePathFilename=" + RemoteExecutePathFilename + ":::" +
                //                 ex);
                //}
                //return false;
            }

        }
    }
}
